package com.example.lib_base

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

abstract class BaseActivity<V:ViewBinding,VM:BaseViewModel<*,*>>:AppCompatActivity() {

    lateinit var vm:VM
    lateinit var vb:V

    abstract fun createVM():VM
    abstract fun createV(): V
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        vm=createVM()
        vb=createV()
        setContentView(vb.root)

        initStateFlow()
        //初始化控件对象
        initView()
        bindState()
        //处理数据以及逻辑
        initData()
    }

    abstract fun bindState()

    abstract fun initData()

    abstract fun initView()

    /**
     * 初始化状态流
     */
    private fun initStateFlow() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                vm.mutableContainer.requestFlow.collect{
                    if(it.request){
                        Log.i("===","请求开始")
                    }else if(it.complete){
                        Log.i("===","请求完成")
                    }else if(it.error){
                        Log.i("===","请求错误")
                    }
                }
            }
        }
    }


}